#import "AppDelegate.h"

/******shark sdk *********/
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKConnector/ShareSDKConnector.h>
//腾讯开放平台（对应QQ和QQ空间）SDK头文件
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>
//微信SDK头文件

//极光推送
#import "JPUSHService.h"
#import <JMessage/JMessage.h>

/******shark sdk  end*********/
//腾讯bug监控
#import <Bugly/Bugly.h>
#import <WXApi.h>
#import "YBTabBarController.h"
//#import <FBSDKMessengerShareKit/FBSDKMessengerSharer.h>
#import <Twitter/Twitter.h>
#import "SPUncaughtExceptionHandler.h"
#import "EBBannerView.h"
//支付宝
#import <AlipaySDK/AlipaySDK.h>

//#include "TiSDKInterface.h"
//发送位置
#import <QMapKit/QMapKit.h>
#import <QMapSearchKit/QMapSearchKit.h>

#import "TXUGCBase.h"
//友盟
#import <UMCommon/UMCommon.h>
#import <UMAnalytics/MobClick.h>
#import "GuideViewController.h"
@import CoreLocation;

#import "RKUUIDManager.h"
#import <TXLiveBase.h>
#import "YBGetVideoObj.h"
#import <notify.h>
#import "YBPrivateVC.h"

#import "YBStorageObj.h"
#import "YBShareView.h"
#import "OpenInstallSDK.h"
//#import "BTAppSwitch.h"
#import "TUIKit.h"
#import <TPNS-iOS/XGPush.h>
#import <TPNS-iOS/XGPushPrivate.h>
#import <ZFPlayer/ZFLandscapeRotationManager.h>
#import <TXLiteAVSDK_Professional/V2TXLivePremier.h>

@interface AppDelegate ()<CLLocationManagerDelegate,WXApiDelegate,JMessageDelegate,OpenInstallDelegate,XGPushDelegate,V2TXLivePremierObserver>
{
    CLLocationManager   *_lbsManager;
    NSNotification * sendEmccBack;
    CGFloat _coverRatio;
}
@property(nonatomic,strong)NSArray *scrollarrays;//轮播
@end
@implementation AppDelegate


/// 在这里写支持的旋转方向，为了防止横屏方向，应用启动时候界面变为横屏模式
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
//    //可以这么写
//    if (self.allowOrentitaionRotation) {
//        return UIInterfaceOrientationMaskAllButUpsideDown;
//    }
//    return UIInterfaceOrientationMaskPortrait;
    ZFInterfaceOrientationMask orientationMask = [ZFLandscapeRotationManager supportedInterfaceOrientationsForWindow:window];
    if (orientationMask != ZFInterfaceOrientationMaskUnknow) {
        return (UIInterfaceOrientationMask)orientationMask;
    }
    /// 这里是非播放器VC支持的方向
    return UIInterfaceOrientationMaskPortrait;

}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//    InstallUncaughtExceptionHandler();
    
    if (@available(iOS 15.0,*)) {
        [UITableView appearance].sectionHeaderTopPadding = 0;
    }
    
    [self setLanguage];
    
    if (![Config getOwnID]) {
        [Config saveUnified:[PublicObj visitorDic]];
    }
    
    NSString *deviceUUID = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    [RKUUIDManager saveUUID:deviceUUID];
    
    [Config saveFirstBonus:@"1"];
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    [[SDWebImageDownloader sharedDownloader] setValue:nil forHTTPHeaderField:@"Accept"];
    [[SDWebImageDownloader sharedDownloader] setValue:h5url forHTTPHeaderField:@"referer"];
    [OpenInstallSDK  initWithDelegate:self];

//    [BTAppSwitch setReturnURLScheme:@"hailongFengbao.payments"];
//    [BTAppSwitch setReturnURLScheme:@"com.yunbao.1v1.payments"];

    self.window = [[UIWindow alloc]initWithFrame:CGRectMake(0,0,_window_width, _window_height)];
    if (@available(iOS 13.0, *)) {
        self.window.overrideUserInterfaceStyle = UIUserInterfaceStyleLight;
    }
    self.window.rootViewController = [[YBNavigationController alloc] initWithRootViewController:[[GuideViewController alloc] init]];
    [self.window makeKeyAndVisible];
    
    if (showCopyright) {
        //启动图版本号、版权信息
        [self setVersionInfo];
        //反复测试延迟1s对版权、版本号展示效果最优
        sleep(1);
    }
    
    //腾讯im
    [[TUIKit sharedInstance]initV2IMSDKWithConfig:[TUIKitConfig defaultConfig]];
    //腾讯tpns推送
    [[XGPush defaultManager] configureClusterDomainName:TXPushClusterDomain];
    [[XGPush defaultManager] startXGWithAccessID:TXPushAccessID accessKey:TXPushAccessKey delegate:self];
    [[XGPush defaultManager] setEnableDebug:YES];

//    [TXLiveBase setLicenceURL:LicenceLiveUrl key:LicenceLiveKey];
    [V2TXLivePremier setLicence:LicenceLiveUrl key:LicenceLiveKey];
    [V2TXLivePremier setObserver:self];
    [TXUGCBase setLicenceURL:LicenceDspURL key:LicenceDspKey];

    //友盟
    [UMConfigure initWithAppkey:UMAppKey channel:UMChannel];
    [MobClick setScenarioType:E_UM_NORMAL];
        
    [IQKeyboardManager sharedManager].enable = YES;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    
    [Bugly startWithAppId:BuglyId];
    
    [self sysLocation];
    [self sendLocation];
    [self thirdPlant];
    
    //推送-IM
    [self setJPush:launchOptions];
    
    //获取后台配置信息
    [BGSetting getBgSettingUpdate:NO maintain:NO eventBack:nil];
    
    [common saveIsStart:@"1"];
    
    //生命周期监听
    [[RKKeepAlive sharedKeepInstance] startAppLifeCycleMonitor];
    [self getNetJudge];
    
    return YES;
}
#pragma mark - V2TXLivePremierObserver
- (void)onLicenceLoaded:(int)result Reason:(NSString *)reason {
    NSLog(@"onLicenceLoaded: result:%d reason:%@", result, reason);
}

-(void)getNetJudge {
    AFNetworkReachabilityManager *netManager = [AFNetworkReachabilityManager sharedManager];
    [netManager startMonitoring];
    [netManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status){
        if (status == AFNetworkReachabilityStatusReachableViaWiFi){
            [PublicObj saveNetReachability:@"wifi"];
        }else if (status == AFNetworkReachabilityStatusReachableViaWWAN){
            [PublicObj saveNetReachability:@"wwan"];
        }else{
            [PublicObj saveNetReachability:@"unknown"];
        }
    }];
}
#pragma mark - 设置语言
-(void)setLanguage {
    //默认值【有语言开发删除此行】
    [[NSUserDefaults standardUserDefaults] setObject:ZH_CN forKey:CurrentLanguage];
    
    // 获取历史
    if (lagType) {
        [[NSUserDefaults standardUserDefaults] setObject:lagType forKey:CurrentLanguage];
    }else{
        BOOL isCn = [[YBLanguageTools shareInstance] isChinese];
        if (isCn) {
            [[NSUserDefaults standardUserDefaults] setObject:ZH_CN forKey:CurrentLanguage];
        }else{
            [[NSUserDefaults standardUserDefaults] setObject:EN forKey:CurrentLanguage];
        }
    }
    [[YBLanguageTools shareInstance] resetLanguage:[[NSUserDefaults standardUserDefaults] objectForKey:CurrentLanguage] withFrom:@"appdelegate"];
}

#pragma mark - 杀进程
- (void)applicationWillTerminate:(UIApplication *)application{
    [StorageConfig clearResTime];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"shajincheng" object:nil];
    if (self.lifeCycleEvent) {
        self.lifeCycleEvent(APPLifeCycle_WillTerminate);
    }
    [[YBYoungManager shareInstance] appKilled];
}
#pragma mark - App进入后台
- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    if (self.lifeCycleEvent) {
        self.lifeCycleEvent(APPLifeCycle_EnterBackground);
    }
    [[YBYoungManager shareInstance] appResignActive];
}
#pragma mark - App将要从后台返回
- (void)applicationWillEnterForeground:(UIApplication *)application {
    
    [application setApplicationIconBadgeNumber:0];
    [JPUSHService setBadge:0];
    
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"rk_paying"]isEqual:@"1"]) {
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"rk_paying"];
        [MBProgressHUD hideHUD];
    }
    
    if (self.lifeCycleEvent) {
        self.lifeCycleEvent(APPLifeCycle_EnterForeground);
    }
    [[YBYoungManager shareInstance] appActive];
}

#pragma mark - 推送-IM
-(void)setJPush:(NSDictionary *)launchOptions{
    
    UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:setting];
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    
    if([[Config getOwnID] intValue]>0) {
        [[YBImManager shareInstance] imLogin];
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bannerDidClick:) name:EBBannerViewDidClickNotification object:nil];

//    if([Config getOwnID]!=nil && ![[Config getOwnID] isEqual:@"-9999"])     {
//        NSString *aliasStr = [NSString stringWithFormat:@"%@PUSH",[Config getOwnID]];
//        [JMSGUser loginWithUsername:[NSString stringWithFormat:@"%@%@",JmessageName,[Config getOwnID]] password:aliasStr completionHandler:^(id resultObject, NSError *error) {
//            if (!error) {
//                NSLog(@"appdelegate-极光IM登录成功");
//            } else {
//                NSLog(@"appdelegate-极光IM登录失败");
//            }
//        }];
//    }
//    //IM
//    [JMessage addDelegate:self withConversation:nil];
//    [JMessage setupJMessage:launchOptions appKey:JpushAppKey channel:Jchannel apsForProduction:isProduction category:nil messageRoaming:YES];
//
//    //推送
//    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
//        //可以添加自定义categories
//        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
//                                                          UIUserNotificationTypeSound |
//                                                          UIUserNotificationTypeAlert)
//                                              categories:nil];
//    }
//    [JPUSHService setupWithOption:launchOptions appKey:JpushAppKey
//                          channel:Jchannel
//                 apsForProduction:isProduction
//            advertisingIdentifier:nil];
//    [JPUSHService setBadge:0];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bannerDidClick:) name:EBBannerViewDidClickNotification object:nil];
    
    //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(jmNot:) name:kJPFNetworkDidSetupNotification object:nil];
}

//极光数据库升级通知
- (void)onDBMigrateStart {
    NSLog(@"onDBmigrateStart in appdelegate");
    _isDBMigrating = YES;
}
//极光数据库升级完成通知
- (void)onDBMigrateFinishedWithError:(NSError *)error {
    NSLog(@"onDBmigrateFinish in appdelegate");
    _isDBMigrating = NO;
    [[NSNotificationCenter defaultCenter] postNotificationName:kDBMigrateFinishNotification object:nil];
}
- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray * _Nullable))restorationHandler{
    //处理通过openinstall一键唤起App时传递的数据
    [OpenInstallSDK continueUserActivity:userActivity];
    //其他第三方回调；
     return YES;
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSLog(@"==============%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);
    [JPUSHService registerDeviceToken:deviceToken];
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        //1.记录registrationID，登陆的时候上传一次
        _jgRegistrationID = registrationID;
        //2.保证打开app的时候再上传一次（上传接口会判断游客和真实用户）
        dispatch_async(dispatch_get_main_queue(), ^{
            [PublicObj updatePushId:registrationID];
        });
    }];
}

#pragma mark - 点击通知进入app调用此方法 开始
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    NSLog(@"userInfo === %@",userInfo);
    
    NSString *contentStr = @"";
    if ([[userInfo valueForKey:@"aps"] isKindOfClass:[NSDictionary class]]) {
        NSDictionary *apsDic = [userInfo valueForKey:@"aps"];
        if ([[apsDic valueForKey:@"alert"] isKindOfClass:[NSDictionary class]]) {
            NSDictionary *alertDic = [apsDic valueForKey:@"alert"];
            contentStr = minstr([alertDic valueForKey:@"body"]);
        }else{
            contentStr = minstr([apsDic valueForKey:@"alert"]);
        }
    }
    
    if(application.applicationState == UIApplicationStateActive) {
        [[EBBannerView bannerWithBlock:^(EBBannerViewMaker *make) {
            make.content = contentStr;//minstr([[userInfo valueForKey:@"aps"] valueForKey:@"alert"]);
            make.object = userInfo;
        }] show];
    }else {
        [self clickNoti:userInfo];
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UIBackgroundFetchResultNewData);
    
}
-(void)bannerDidClick:(NSNotification *)notifi {
    NSDictionary *userInfo = [notifi object];
    [self clickNoti:userInfo];
}

-(void)clickNoti:(NSDictionary *)userInfo {
    YBWeakSelf;
    NSString *not_type = minstr([userInfo valueForKey:@"type"]);
    NSDictionary *not_dic = [NSDictionary dictionary];
    //获取推送详情---> 发布视频:1 直播开播:2;
    if ([not_type isEqual:@"1"] && [[userInfo valueForKey:@"videoinfo"] isKindOfClass:[NSDictionary class]]) {
        not_dic = [userInfo valueForKey:@"videoinfo"];
    }
    if ([not_type isEqual:@"2"] && [[userInfo valueForKey:@"userinfo"] isKindOfClass:[NSDictionary class]]) {
        not_dic = [userInfo valueForKey:@"userinfo"];
    }
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"isLiveing"]) {
        [MBProgressHUD showPop:YZMsg(@"正在直播中,无法退出")];
        return;
    }
    //需求:只有是视频的时候处理，直播去首页
    if ([not_type isEqual:@"1"]) {
        [YBGetVideoObj lookManeger].fromWhere = @"AppNoti";
        [YBGetVideoObj lookManeger].videoID = minstr([not_dic valueForKey:@"videoid"]);
        [YBGetVideoObj lookManeger].playIndex = 0;
        [YBGetVideoObj lookManeger].videoList = @[].mutableCopy;
        [YBGetVideoObj lookManeger].paging = 1;
        [YBGetVideoObj lookManeger].baseUrl = @"";
        [[YBGetVideoObj lookManeger]goLookVC];
    }
    if ([not_type isEqual:@"2"]) {
        if ([[NSUserDefaults standardUserDefaults] boolForKey:@"isPlaying"]) {
            NSDictionary *contentDic = @{@"title":YZMsg(@"提示"),
                                        @"msg":YZMsg(@"是否退出直播间"),
                                        @"left":YZMsg(@"取消"),
                                        @"right":YZMsg(@"确定")};
            [YBAlertView showAlertView:contentDic complete:^(int eventType) {
                if (eventType == 1) {
                    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isPlaying"];
                    [weakSelf goHomeUI];
                }
            }];
        }else{
            [weakSelf goHomeUI];
        }
    }
}
-(void)goHomeUI {
    [PublicObj resetVC:[[YBTabBarController alloc]initWithAlert:NO]];
}
#pragma mark - 点击通知进入app调用此方法 结束

#pragma mark - 发送位置
-(void)sendLocation {
    [QMapServices sharedServices].apiKey = TencentKey;
    [[QMSSearchServices sharedServices] setApiKey:TencentKey];
}

#pragma mark - 定位
-(void)sysLocation{
    [[RKLBSManager shareManager] startLocation];
}
/*
-(void)sysLocation{
    if (!_lbsManager) {
        _lbsManager = [[CLLocationManager alloc] init];
        [_lbsManager setDesiredAccuracy:kCLLocationAccuracyBest];
        _lbsManager.delegate = self;
        // 兼容iOS8定位
        SEL requestSelector = NSSelectorFromString(@"requestWhenInUseAuthorization");
        if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
            NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
            UIAlertController *alertContro = [UIAlertController alertControllerWithTitle:nil message:[NSString stringWithFormat:@"%@%@%@",YZMsg(@"打开“定位服务”来允许“"),[infoDictionary objectForKey:@"CFBundleDisplayName"],YZMsg(@"确定您的位置")] preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:YZMsg(@"设置") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            }];
            [alertContro addAction:cancleAction];
            UIAlertAction *sureAction = [UIAlertAction actionWithTitle:YZMsg(@"取消") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            }];
            [alertContro addAction:sureAction];
            [self.window.rootViewController presentViewController:alertContro animated:YES completion:nil];
            
        }else{
            
            if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined && [_lbsManager respondsToSelector:requestSelector]) {
                [_lbsManager requestWhenInUseAuthorization];  //调用了这句,就会弹出允许框了.
            } else {
                [_lbsManager startUpdatingLocation];
            }
        }
    }
}

- (void)stopLbs {
    [_lbsManager stopUpdatingHeading];
    _lbsManager.delegate = nil;
    _lbsManager = nil;
}
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    if (status == kCLAuthorizationStatusRestricted || status == kCLAuthorizationStatusDenied) {
        [self stopLbs];
    } else {
        [_lbsManager startUpdatingLocation];
    }
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    [self stopLbs];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    CLLocation *newLocatioin = locations[0];
    
    NSString* locationLat = [NSString stringWithFormat:@"%f",newLocatioin.coordinate.latitude];
    NSString* locationLng = [NSString stringWithFormat:@"%f",newLocatioin.coordinate.longitude];
    
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:newLocatioin completionHandler:^(NSArray *placemarks, NSError *error) {
        if (!error) {
            CLPlacemark *placeMark =  placemarks[0];
            NSString *city = placeMark.locality;
           
            [cityDefault saveLocationLat:locationLat];
            [cityDefault saveLocationLng:locationLng];
            [cityDefault saveLocationCity:city];
        }
    }];
    [self stopLbs];
}
*/
#pragma mark - 分享
-(void)thirdPlant{
    
    [ShareSDK registPlatforms:^(SSDKRegister *platformsRegister) {
        [platformsRegister setupQQWithAppId:QQAppId appkey:QQAppKey enableUniversalLink:NO universalLink:QQUniversalLink];
        [platformsRegister setupWeChatWithAppId:WechatAppId appSecret:WechatAppSecret universalLink:WechatUniversalLink];
        
    }];
    
}

#pragma makr - 支付
// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options {
    [OpenInstallSDK handLinkURL:url];
    if ([url.scheme localizedCaseInsensitiveCompare:@"com.yunbao.1v1.payments"] == NSOrderedSame) {
        return true;
//        [BTAppSwitch handleOpenURL:url options:options];
    }
//    if ([url.scheme localizedCaseInsensitiveCompare:@"hailongFengbao.payments"] == NSOrderedSame) {
//            return [BTAppSwitch handleOpenURL:url options:options];
//        }

    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            [[NSNotificationCenter defaultCenter]postNotificationName:@"aliPayNot" object:nil userInfo:resultDic];
        }];
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            // 解析 auth code
            NSString *result = resultDic[@"result"];
            NSString *authCode = nil;
            if (result.length>0) {
                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                for (NSString *subResult in resultArr) {
                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                        authCode = [subResult substringFromIndex:10];
                        break;
                    }
                }
            }
            NSLog(@"授权结果 authCode = %@", authCode?:@"");
        }];
    }else if ([url.host isEqual:@"pay"]){
        return [WXApi handleOpenURL:url delegate:(id<WXApiDelegate>)self];
    }
    return YES;
}
-(void)onResp:(BaseResp *)resp{
    //支付返回结果，实际支付结果需要去微信服务器端查询
    NSString *strMsg;
    NSString *code;
    switch (resp.errCode) {
        case WXSuccess:{
            code = @"1";
            strMsg = YZMsg(@"支付成功");
            NSLog(@"支付成功－PaySuccess，retcode = %d", resp.errCode);
        }break;
        case WXErrCodeUserCancel:{
            code = @"0";
            strMsg = YZMsg(@"支付取消");
            NSLog(@"支付取消，retcode = %d", resp.errCode);
        }break;
        default:{
            code = @"-1";
            strMsg = YZMsg(@"支付失败");
            NSLog(@"错误，retcode = %d, retstr = %@", resp.errCode,resp.errStr);
        }break;
    }
    NSDictionary *dic = @{
                          @"msg":strMsg,
                          @"code":code
                          };
    [[NSNotificationCenter defaultCenter] postNotificationName:@"wxPayNot" object:nil userInfo:dic];
}

#pragma mark - 启动图版本号、版权信息
-(void)setVersionInfo {
    UIImageView *launchImageView = [[UIImageView alloc] initWithFrame:self.window.bounds];
    launchImageView.image = [PublicObj getLaunchImage];
    [self.window addSubview:launchImageView];
    [self.window bringSubviewToFront:launchImageView];
    
    UILabel *copyright = [[UILabel alloc]init];
    copyright.text = copyrightDes;
    copyright.font = SYS_Font(10);
    copyright.textAlignment = NSTextAlignmentCenter;
    copyright.textColor = [UIColor whiteColor];
    [launchImageView addSubview:copyright];
    [copyright mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(launchImageView.mas_width);
        make.height.mas_equalTo(20);
        make.bottom.mas_equalTo(launchImageView.mas_bottom).offset(-10-ShowDiff/2);
        make.centerX.mas_equalTo(launchImageView.mas_centerX);
    }];
    
    UILabel *vesionLabel = [[UILabel alloc] init];
    //获取当前设备中应用的版本号
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    //NSString *currentVersion = [infoDic objectForKey:@"CFBundleShortVersionString"];//大版本
    NSString *currentVersion = [infoDic objectForKey:@"CFBundleVersion"];//小版本
    NSString *app_Name = [infoDic objectForKey:@"CFBundleDisplayName"];
    vesionLabel.text = [NSString stringWithFormat:@"%@ V %@",app_Name,currentVersion];
    vesionLabel.font = SYS_Font(10);
    vesionLabel.textColor = copyright.textColor;
    vesionLabel.textAlignment = NSTextAlignmentCenter;
    [launchImageView addSubview:vesionLabel];
    [vesionLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(launchImageView.mas_width);
        make.height.mas_equalTo(20);
        make.bottom.mas_equalTo(copyright.mas_bottom).offset(-20);
        make.centerX.mas_equalTo(launchImageView.mas_centerX);
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:0.5 animations:^{
            launchImageView.alpha = 0.0;
            launchImageView.transform = CGAffineTransformMakeScale(1.2, 1.2);
        } completion:^(BOOL finished) {
            [launchImageView removeFromSuperview];
        }];
    });
}

#pragma mark - 音视频操作 开始

-(void)startUpload {
    YBWeakSelf;
    [[YBStorageObj storageManeger]getCOSType:^(int code) {
        if (code == 0) {
            [weakSelf startUploadOOOOOO];
        }
    }];
}

-(void)startUploadOOOOOO {
    [self resetProgress];
    
    _coverRatio = 1.778;
    if (_originalCover) {
        CGFloat fixelW = CGImageGetWidth(_originalCover.CGImage);
        CGFloat fixelH = CGImageGetHeight(_originalCover.CGImage);
        _coverRatio = fixelH/fixelW;
    }

    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    YBWeakSelf;
    //原始图片
    dispatch_group_async(group, queue, ^{
        UIImage *saveImg = _originalCover;
        [[NSNotificationCenter defaultCenter]postNotificationName:@"uploadCoverNot" object:saveImg];
        NSString *imageName = [PublicObj getNameBaseCurrentTime:@"_origin.png"];
        [[YBStorageObj storageManeger]yb_storageImg:saveImg andName:imageName progress:^(CGFloat percent) {
            _originalCoverPro = percent;
            [weakSelf ybUploadProgress];
        }complete:^(int code, NSString *key) {
            _cosFinishCoverPath = minstr(key);
            dispatch_semaphore_signal(semaphore);
        }];
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    });
    
    //原始视频
    dispatch_group_async(group, queue, ^{
        NSString *videoName = [PublicObj getNameBaseCurrentTime:@"_origin.mp4"];
        NSString *videoPath = _originalVdieoPath;
        [[YBStorageObj storageManeger]yb_storageVideoOrVoice:videoPath andName:videoName progress:^(CGFloat percent) {
            _originalVideoPro = percent;
            [weakSelf ybUploadProgress];
        }complete:^(int code, NSString *key) {
            _cosFinishVideoPath = minstr(key);
            dispatch_semaphore_signal(semaphore);
        }];
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    });
    
    //水印视频
    if (_originalMKVideoPath) {
        _uploadNum = 3;
        dispatch_group_async(group, queue, ^{
            NSString *videoName = [PublicObj getNameBaseCurrentTime:@"_water.mp4"];
            [[YBStorageObj storageManeger]yb_storageVideoOrVoice:_originalMKVideoPath andName:videoName progress:^(CGFloat percent) {
                _mkVideoPro = percent;
                [weakSelf ybUploadProgress];
            }complete:^(int code, NSString *key) {
                _cosFinishMKVideoPath = minstr(key);
                dispatch_semaphore_signal(semaphore);
            }];
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        });
    }
    
    dispatch_group_notify(group, queue, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf resetProgress];
            [weakSelf requstAPPServceTitle:_videoTitle andVideo:_cosFinishVideoPath andImage:_cosFinishCoverPath andWaterName:_cosFinishMKVideoPath];
        });
        NSLog(@"任务完成执行");
    });
}
-(void)resetProgress {
    _originalVideoPro = 0.0;
    _originalCoverPro = 0.0;
    _mkVideoPro = 0.0;
    _uploadNum = 2;
    _allUploadPro = 0.0;
}
-(void)ybUploadProgress{
    _allUploadPro = (_originalCoverPro+_originalVideoPro+_mkVideoPro)/_uploadNum;
    NSLog(@"allll:%f",_allUploadPro);
    [[NSNotificationCenter defaultCenter]postNotificationName:@"uploadProNot" object:@(_allUploadPro)];
}

#pragma mark - 上传七牛或者腾讯云存储成功后把视频地址、封面地址反馈给自己的服务器
-(void)requstAPPServceTitle:(NSString *)myTile andVideo:(NSString *)video andImage:(NSString *)image andWaterName:(NSString *)water {
   
    if ([PublicObj checkNull:_cosFinishVideoPath] || [PublicObj checkNull:_cosFinishCoverPath] || (![PublicObj checkNull:_originalMKVideoPath] && [PublicObj checkNull:_cosFinishMKVideoPath])) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showPop:@"发布失败"];
        return;
    }
    YBWeakSelf;
//    NSString *videoClassID = [PublicObj checkNull:minstr([_videoClassDic valueForKey:@"id"])]?@"0":minstr([_videoClassDic valueForKey:@"id"]);
    NSMutableDictionary *pullDic = @{
                              @"uid":[Config getOwnID],
                              @"token":[Config getOwnToken],
                              @"title":minstr(myTile),
                              @"href":minstr(video),
                              @"thumb":minstr(image),
                              //@"lng":[NSString stringWithFormat:@"%@",[cityDefault getLocationLng]],
                              //@"lat":[NSString stringWithFormat:@"%@",[cityDefault getLocationLat]],
                              //@"city":[NSString stringWithFormat:@"%@",[cityDefault getLocationCity]?[cityDefault getLocationCity]:@"好像在火星"],
                              @"lng":minstr(_videoLng),
                              @"lat":minstr(_videoLat),
                              @"city":minstr(_videoCity),
                              @"music_id":_musicID ? _musicID : @"0",
                              @"labelid":_topicID ? _topicID:@"0",
                              //@"goodsinfo": _shopJsonStr ?_shopJsonStr:@"",
                              @"goodsid":_goodsID,
                              @"href_w":water?water:@"",
                              @"classid":_videoClassID ?_videoClassID:@"0" ,
                              @"cityclass_id":_sameCityClassId ? _sameCityClassId:@"0",
                              @"coin":_videoChargeNum?_videoChargeNum:@"0",
                              @"anyway":[NSString stringWithFormat:@"%.3f",_coverRatio],
                              @"is_userad":_is_userad,
                              @"userad_url":_userad_url
                              }.mutableCopy;
    
    [WYNetworking postWithUrl:@"Video.setVideo" Dic:pullDic Suc:^(int code, id info, NSString *msg) {
        if (code == 0) {
            [MBProgressHUD hideHUD];
            /*
            NSString *audit_switch = [NSString stringWithFormat:@"%@",[common getAuditSwitch]];
            if ([audit_switch isEqual:@"1"]) {
                [MBProgressHUD showSuccess:@"上传成功，请等待审核"];
            }else{
                [MBProgressHUD showSuccess:@"发布成功"];
            }
            */
            NSString *audit_switch = [NSString stringWithFormat:@"%@",[common getAuditSwitch]];
            if ([audit_switch isEqual:@"1"]) {
                [MBProgressHUD showSuccess:YZMsg(@"上传成功，请等待审核")];
            }else{
                BOOL isOk = [[NSFileManager defaultManager] removeItemAtPath:_originalVdieoPath error:nil];
                if (_originalMKVideoPath) {
                    [[NSFileManager defaultManager] removeItemAtPath:_originalMKVideoPath error:nil];
                }
                NSLog(@"%d shanchushanchushanchu",isOk);
                NSDictionary *infoDic = [info firstObject];
                NSLog(@"====%@",infoDic);
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf uploadSuc:infoDic];
                });
            }
        }else {
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:msg];
        }
    } Fail:^(id fail) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:@"网络连接断开，视频上传失败"];
    }];
}

-(void)uploadSuc:(NSDictionary *)dic {
    NSString *showSharePop = minstr([[NSUserDefaults standardUserDefaults]objectForKey:@"show_share_pop"]);
    UIApplicationState state = [UIApplication sharedApplication].applicationState;
    NSArray *shareA = [NSArray arrayWithArray:[common share_type]];
    if (state != UIApplicationStateActive || ![showSharePop isEqual:@"1"] || shareA.count<=0){
        return;
    }
    //分享
    NSString *videoId = minstr([dic valueForKey:@"id"]);
    NSString * imageThumb = minstr([dic valueForKey:@"thumb_s"]);
    NSString *videoTitle = minstr([dic valueForKey:@"title"]);
    NSString *shareDes = [common video_share_des];
    if (![PublicObj checkNull:videoTitle]) {
        shareDes = videoTitle;
    }
    NSDictionary *shareDic = @{@"id":videoId,@"thumb_s":imageThumb,@"publish_des":shareDes,@"userinfo":@{@"user_nickname":[Config getOwnNicename]}};
    [YBShareView showMidPopShareType:RKShareType_VPMidPop parameter:shareDic commplete:^(int codeEvent, NSString *nums) {
        
    }];
    
}


#pragma mark - 音视频操作结束
//通过openInstall获取已经安装App被唤醒时的参数（如果是通过渠道页面唤醒App时，会返回渠道编号）
-(void)getWakeUpParams:(OpeninstallData *)appData{
    if (appData.data) {//(动态唤醒参数)
        //e.g.如免填邀请码建立邀请关系、自动加好友、自动进入某个群组或房间等
    }
    if (appData.channelCode) {//(通过渠道链接或二维码唤醒会返回渠道编号)
        //e.g.可自己统计渠道相关数据等
    }
    NSLog(@"OpenInstallSDK:\n动态参数：%@;\n渠道编号：%@",appData.data,appData.channelCode);
}


// 统一接收消息的回调
/// @param notification 消息对象(有2种类型NSDictionary和UNNotification具体解析参考示例代码)
/// @note 此回调为前台收到通知消息及所有状态下收到静默消息的回调（消息点击需使用统一点击回调）
/// 区分消息类型说明：xg字段里的msgtype为1则代表通知消息msgtype为2则代表静默消息
- (void)xgPushDidReceiveRemoteNotification:(nonnull id)notification withCompletionHandler:(nullable void (^)(NSUInteger))completionHandler{
    if ([notification isKindOfClass:[UNNotificationResponse class]]) {
        NSLog(@"aaaaaaaaaaa[TPNS Demo] click notification: %@", ((UNNotificationResponse *)notification).notification.request.content.userInfo);
    } else if ([notification isKindOfClass:[NSDictionary class]]) {
        NSLog(@"bbbbbbbbb[TPNS Demo] click notification: %@", notification);
    }
 /// code
}
 /// 统一点击回调
/// @param response 如果iOS 10+/macOS 10.14+则为UNNotificationResponse，低于目标版本则为NSDictionary
- (void)xgPushDidReceiveNotificationResponse:(nonnull id)response withCompletionHandler:(nonnull void (^)(void))completionHandler {
    if ([response isKindOfClass:[UNNotificationResponse class]]) {
        NSLog(@"[TPNS Demo] click notification: %@", ((UNNotificationResponse *)response).notification.request.content.userInfo);
        NSDictionary *responeDic = ((UNNotificationResponse *)response).notification.request.content.userInfo;
        NSDictionary *userInfo =[PublicObj dictionaryWithJsonString:minstr([responeDic  valueForKey:@"custom"])];
        
        if ([minstr([userInfo valueForKey:@"type"]) isEqual:@"1"]) {

//            if([[userInfo valueForKey:@"userinfo"] valueForKey:@"uid"] != nil)
//            {
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"jinruzhibojiantongzhi" object:[userInfo valueForKey:@"userinfo"]];
//            }
        }else if ([minstr([userInfo valueForKey:@"type"]) isEqual:@"2"]) {
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"system_notification" object:nil];
//            [self goMsgVC];
        }

        
        
    } else if ([response isKindOfClass:[NSDictionary class]]) {
        NSLog(@"[TPNS Demo] click notification: %@", response);
    }

  /// code
}
/**
@brief 注册推送服务回调
@param deviceToken APNs 生成的 Device Token
@param xgToken TPNS 生成的 Token，推送消息时需要使用此值。TPNS 维护此值与 APNs 的 Device Token 的映射关系
@param error 错误信息，若 error 为 nil 则注册推送服务成功
@note TPNS SDK1.2.6.0+
*/
- (void)xgPushDidRegisteredDeviceToken:(nullable NSString *)deviceToken xgToken:(nullable NSString *)xgToken error:(nullable NSError *)error{
    NSLog(@"xgToken------:%@ ---errror:%@",xgToken, error);
    if ([Config getOwnID]) {
        [[XGPushTokenManager defaultTokenManager] upsertAccountsByDict:@{@(0):[Config getOwnID]}];
    }
    
}
/// 注册推送服务失败回调
/// @param error 注册失败错误信息
/// @note TPNS SDK1.2.7.1+
-(void)xgPushDidFailToRegisterDeviceTokenWithError:(nullable NSError *)error {
}

@end
